import { defineStore } from "pinia";
import { Names } from "./store-name";
import { useRequest } from "alova";
import { queryDbs, searchCache, queryTableName, executeSql } from '../api/tool';
import type { TCacheData, TCacheKey, TColInfo, TDatabase, TSqlReq, TTableItem, TTableReq } from "@/typing/tool";
import { replaceTextarea } from '@/utils/util'


const useToolStore = defineStore(Names.TOOL, {
  state() {
      return {
        cacheData: <TCacheData>{TTL: '', val: ''},
        databases: <TDatabase[]>[],
        tables: <TTableItem[]>[],
        isTableData: false,
        colInfoList: <TColInfo[]>[],
        sqlData: <any>[]
      }
  },

  getters: {
    getCache(state) {
      return {
        ttl: state.cacheData.TTL.split(': ')[1],
        val: state.cacheData.val
      }
    },
    getDbs(state) {
      return state.databases.map(item => {
        return {
          name: item.dbName,
          code: item.dbName
        }
      })
    },
    getTables(state) {
      return state.tables.map(item => {
        return {
          name: item.tableComment,
          code: item.tableName,
        }
      })
    },
    getSql(state) {

      return state.sqlData[0]?.['Create Table'] || ''
    }
  },
  actions: {
    searchCache(data: TCacheKey) {
      const { onSuccess } = useRequest(searchCache(data))
      onSuccess(({ data }: { data: any }) => {
        console.log('searchCache', data)
        this.cacheData = data.data as TCacheData
      })

    },
    queryDbs(fn: Function) {
      const { onSuccess } = useRequest(queryDbs())
      onSuccess(({ data }: { data: any }) => {
        console.log('queryDbs', data)
        this.databases = data.data.list as TDatabase[]
        fn && fn(this.databases[0])
      })
    },
    queryTableName(data: TTableReq) {
      const { onSuccess } = useRequest(queryTableName(data))
      onSuccess(({ data }: { data: any }) => {
        console.log('queryTableName', data)
        this.tables = data.data.list as TTableItem[]
      })

    },
    executeSql(data: TSqlReq, isTableData: boolean) {
      const { onSuccess } = useRequest(executeSql(data))
      onSuccess(({ data }: { data: any }) => {
        this.isTableData = isTableData
        this.colInfoList = data.data.colsInfo as TColInfo[]
        this.sqlData = data.data.list
        console.log('executeSql', data)
      })

    },
  },
})

export default useToolStore
